// server.cpp
#include "server.h"

Server::Server(QObject *parent) : QObject(parent)
{
    tcpServer = new QTcpServer(this);
    connect(tcpServer, &QTcpServer::newConnection, this, &Server::onNewConnection);
}

Server::~Server()
{
    stopServer();
}

void Server::startServer(quint16 port)
{
    if (!tcpServer->listen(QHostAddress::Any, port)) {
        qDebug() << "Server could not start! Error:" << tcpServer->errorString();
    } else {
        qDebug() << "Server started on port" << port;
    }
}

void Server::stopServer()
{
    // 断开所有客户端连接
    for (auto it = clientThreads.begin(); it != clientThreads.end(); ++it) {
        QTcpSocket *socket = it.key();
        if (socket) {
            socket->disconnectFromHost();
            if (socket->state() != QTcpSocket::UnconnectedState) {
                socket->waitForDisconnected();
            }
            socket->deleteLater();
        }
        
        QThread *thread = it.value();
        if (thread) {
            thread->quit();
            thread->wait();
            thread->deleteLater();
        }
    }
    clientThreads.clear();
    
    // 停止监听
    if (tcpServer->isListening()) {
        tcpServer->close();
        qDebug() << "Server stopped listening";
    }
}

void Server::onNewConnection()
{
    QTcpSocket *socket = tcpServer->nextPendingConnection();
    
    qDebug() << "New connection from:" << socket->peerAddress().toString() 
             << ":" << socket->peerPort();
    
    connect(socket, &QTcpSocket::disconnected, this, &Server::onClientDisconnected);
    connect(socket, &QTcpSocket::readyRead, this, &Server::onReadyRead);
    
    // 为每个新连接创建线程和WorkerA
    QThread *thread = new QThread();
    WorkerA *worker = new WorkerA();
    
    worker->moveToThread(thread);
    
    // 存储socket和线程的映射关系
    clientThreads.insert(socket, thread);
    
    // 当线程启动时，调用worker的doWork函数
    connect(thread, &QThread::started, [worker, socket]() {
        worker->doWork(socket);
    });
    
    // 当worker完成时，线程退出
    connect(worker, &WorkerA::workFinished, thread, &QThread::quit);
    
    // 当线程结束时，删除worker和自身
    connect(thread, &QThread::finished, worker, &WorkerA::deleteLater);
    connect(thread, &QThread::finished, thread, &QThread::deleteLater);
    
    // 线程结束后从map中移除
    connect(thread, &QThread::finished, [this, socket]() {
        clientThreads.remove(socket);
        qDebug() << "Thread for socket" << socket << "cleaned up";
    });
    
    thread->start();
}

void Server::onClientDisconnected()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
    if (socket) {
        qDebug() << "Client disconnected:" << socket->peerAddress().toString() 
                 << ":" << socket->peerPort();
        
        // 从map中查找对应的线程
        QThread *thread = clientThreads.value(socket, nullptr);
        if (thread) {
            thread->quit();
            thread->wait();
        }
        
        socket->deleteLater();
    }
    
    qDebug() << "Current connections:" << clientThreads.size();
    qDebug() << "Server continues to listen for new connections...";
}

void Server::onReadyRead()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
    if (socket) {
        QByteArray data = socket->readAll();
        qDebug() << "Received from" << socket->peerAddress().toString() 
                 << ":" << QString(data);
        
        // 回显给客户端
        if (socket->state() == QTcpSocket::ConnectedState) {
            socket->write(QString("Echo: " + QString(data)).toUtf8());
        }
    }
}
